<template>
	<view >
		<!-- 顶部导航栏 -->
		<view class="navigate-bar">
			<view class="navigate-bar-app"></view>
			<view class="navigate-bar-main">
				<view class="navigate-bar-left">
					<view class="navigate-bar-left-avatar" @tap="showDrawer()">
						<image class="navigate-bar-left-avatar-image" :src="loginUserInfo.avatar"></image>
						<view v-if="!isSocketOpen" class="navigate-bar-left-avatar-red-dot"></view>
						<view v-if="isSocketOpen" class="navigate-bar-left-avatar-green-dot"></view>
					</view>
				</view>
				<view class="navigate-bar-middle">
					消息列表
				</view>
				<view class="navigate-bar-right">
					<image @tap="gotoSearch()" class="navigate-bar-right-icon" src="../../static/icon/search.png"></image>
				</view>
			</view>
		</view>
		<!-- 顶部占位标签 -->
		<view class="navigate-bar-space"></view>
		
		<view style="padding: 20rpx;">
			<u--input
				placeholder="搜索"
				border="surround"
				shape="circle"
				v-model="keyword"
				style="width: 90%;height: 40rpx;margin-left: auto;margin-right: auto;background-color: #f3f3f3;"
			></u--input>
		</view>
	
		<view class="list">
			<view class="flex_col" @longpress="onLongPress" :class="{'active':pickerUserIndex==index}" @tap="listTap(item)" v-for="(item,index) in sessionList"
			 :key="index" :data-index="index">
				<view class="avatar-container">
					<image :src="item.avatar" mode="aspectFill" style="border-radius: 10%;"></image>
					<u-badge style="position: absolute;right: -10upx;top: -10upx;" :type="'error'" max="99" :value="item.unread"></u-badge>
				</view>
				<view class="flex_grow">
					<view class="flex_col">
						<view class="flex_grow">{{item.name}}</view>
						<view class="time">{{timeShowFormat(item.updateTime)}}</view>
					</view>
					<view class="info">{{item.lastMessage}}</view>
				</view>
			</view>
		</view>
		<view class="shade" v-show="showShade" @tap="hidePop">
			<view class="pop" :style="popStyle" :class="{'show':showPop}">
				<view v-for="(item,index) in popButton" :key="index" @tap="pickerMenu" :data-index="index">{{item}}</view>
			</view>
		</view>
		
		
		
		
		
		
		
		<!-- 底部导航栏高度层 -->
		<view style="height: 50px;"></view>
		<!-- 底部导航栏 -->
		<u-tabbar
			:value="value"
			:placeholder="false"
			@change="name => changeTab(name)"
			:fixed="true"
			:safeAreaInsetBottom="false"
		>
			<u-tabbar-item text="消息" icon="chat-fill" :badge="totalUnread.message"></u-tabbar-item>
			<u-tabbar-item text="联系人" icon="account-fill" :badge="totalUnread.notice"></u-tabbar-item>
		</u-tabbar>
		
		<!-- 侧边栏 -->
		 <unidrawer ref="draw" :mask="true" :width="280" :mode="'left'">
			<sideview></sideview>
		</unidrawer>
		
		<!-- 上传头像 -->
		<u-popup :show="uploadShow" :round="10" mode="center" @close="close" @open="open">
			<view style="padding: 40rpx;text-align: center;">
				<view style="color: darkgrey;">请先设置你的头像</view>
				<view style="margin-top: 40rpx;">
					<u-avatar style="margin-left: 20%;" @tap="chooseYourAvatar()" size="80" :src="selectedImage"></u-avatar>
				</view>
			   <u-button style="margin-top: 40rpx;" @tap="uploadYourAvatar()" v-show="selectedImage!=''" size="small" type="success">上传</u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import timeUtil from '@/util/timeUtil.js';
	import stringUtil from '@/util/stringUtil.js';
	import userRequest from '@/api/user.js';
	import {mapGetters} from 'vuex';
	import requestUrl from '@/api/url.js';
	import websocket from '@/api/websocket.js';
	import $store from '@/store/index.js';
	import unidrawer from '@/uni_modules/uni-drawer/components/uni-drawer/uni-drawer.vue';
	import sideview from '@/components/sideView/sideview.vue';
	export default {
		components:{
			unidrawer:unidrawer,
			sideview:sideview
		},
		data() {
			return {
				keyword:'',
				uploadShow: false,
				selectedImage: '',
				title: '开发者：小克 , qq交流群：1021275878',
				show: false,
				selectedAvartar: null,
				maxImageMB: 3,
				register: {
					nickname: '',
					password1: '',
					password2: ''
				},
				tip: '',
				loginShow: false,
				login:{
					nickname: '',
					password: ''
				},
				value: 0,
				/* 窗口尺寸 */
				winSize: {},
				/* 显示遮罩 */
				showShade: false,
				/* 显示操作弹窗 */
				showPop: false,
				/* 弹窗按钮列表 */
				popButton: ["tip"],
				/* 弹窗定位样式 */
				popStyle: "",
				/* 选择的用户下标 */
				pickerUserIndex: -1
			}
		},
		computed:{
			...mapGetters(['loginUserInfo','isSocketOpen','sessionList','totalUnread'])
		},
		watch:{
			keyword: function(){
				uni.showToast({
					icon:'none',
					title:'这个没用,你上当了~'
				})
			}
		},
		///刷新
		onPullDownRefresh() {
			///重新获取连接websocket
			if(!$store.state.isSocketOpen){
				websocket.initConnect()
			}
			///从新获取消息列表
			$store.dispatch('getFriendList')
			setTimeout(()=>{
				if($store.state.isSocketOpen){
					uni.showToast({
						icon:'success',
						title:'刷新成功！'
					})
				}
				else{
					uni.showToast({
						icon:'error',
						title:'刷新失败！'
					})
				}
				uni.stopPullDownRefresh()
			},500)
		},
		onLoad() {
			uni.hideTabBar();
			this.getWindowSize();
			
			// #ifdef H5
			document.onLong = function(e) {
				var e = e || window.event;
				e.preventDefault();
			};
			// #endif
			
			///如果用户没有头像 则需要上传头像
			if(this.loginUserInfo.avatar==''){
				this.uploadShow = true;
			}
		},
		methods: {
			timeShowFormat(time){
				return timeUtil.timeShowFormat(timeUtil.getFormatTime(Number(time)));
			},
			close(){},open(){},
			chooseYourAvatar(){
				let that = this
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album','camera'], //从相册选择
					success: function (res) {
						//console.log(res.tempFilePaths[0])
						if(3*1048576 < res.tempFiles[0].size){
							uni.showToast({
								icon:'none',
								title:'图片请限制在'+3+'MB以内'
							})
						}else{
							that.selectedImage = res.tempFilePaths[0];
						}
					}
				});
			},
			uploadYourAvatar() {
				uni.showLoading({
					title:'请等待...'
				})
				let _this = this
				uni.uploadFile({
					url: requestUrl.getUrl()+'ddchat/image/uploadAvatar', // 仅为示例，非真实的接口地址
					filePath: this.selectedImage,
					name: 'image',
					formData: {
						userId: $store.state.loginUserInfo.id
					},
					success: (res) => {
						let data = JSON.parse(res.data)
						if(!data.success) uni.showToast({
							title:'图片上传失败！',
							icon:'none'
						})
						else{
							this.updateAvater(data)
						}
					}
				});
			},
			async updateAvater(data){
				let res = await userRequest.update({
					id: this.loginUserInfo.id,
					avatar: requestUrl.getUrl()+data.data.compressUrl,
					background: requestUrl.getUrl()+data.data.url
				})
				uni.hideLoading();
				uni.showToast({
					icon:'none',
					title:'上传成功！'
				})
				$store.state.loginUserInfo = res.data;
				uni.setStorageSync('LOGIN_USER_INFO', res.data);
				this.uploadShow = false
				////加入公共聊天室
				
				///构造websocket消息
				let m = {
					 userId : this.loginUserInfo.id,
					 groupId : '49911198753361920'
				}
				let msg = {
					 type: 'join-group',
					 data: m
				}
				//uni.sendSocketMessage({
				//	data: JSON.stringify(msg),
				//	fail(res) {
				//		uni.showToast({
				//			icon:'error',
				//			title:'发送失败'
				//		})
				//	}
				//})
				
				
				
			},
			//去搜索页面
			gotoSearch(){
				uni.navigateTo({
					url:'/pages/search/search'
				})
			},
			//显示抽屉
			showDrawer(){
				this.$refs.draw.open();
			},
			hideDrawer(){
				this.$refs.draw.close();
			},
			changeTab(e){
				switch(e){
					case 1:
						uni.switchTab({
							url:'/pages/list/friend-list'
						})
						break;
				}
			},
			/* 列表触摸事件 */
			listTap(item) {
				//console.log(item)
				/* 因弹出遮罩问题，所以需要在遮罩弹出的情况下阻止列表事件的触发 */
				if (this.showShade) {
					return;
				}
				//
				//console.log("列表触摸事件触发")
				if(item.type=='person'){
					$store.state.chattingUserInfo = item;
					uni.navigateTo({
						url:'/pages/chat/person-chat'
					})
				}else{
					$store.state.chattingGroupInfo = item;
					//debugger
					uni.navigateTo({
						url:'/pages/chat/group-chat'
					})
				}
			},
			/* 获取窗口尺寸 */
			getWindowSize() {
				uni.getSystemInfo({
					success: (res) => {
						this.winSize = {
							"witdh": res.windowWidth,
							"height": res.windowHeight
						}
					}
				})
			},
			/* 长按监听 */
			onLongPress(e) {
				let [touches, style, index] = [e.touches[0], "", e.currentTarget.dataset.index];
			
				/* 因 非H5端不兼容 style 属性绑定 Object ，所以拼接字符 */
				if (touches.clientY > (this.winSize.height / 2)) {
					style = `bottom:${this.winSize.height-touches.clientY}px;`;
				} else {
					style = `top:${touches.clientY}px;`;
				}
				if (touches.clientX > (this.winSize.witdh / 2)) {
					style += `right:${this.winSize.witdh-touches.clientX}px`;
				} else {
					style += `left:${touches.clientX}px`;
				}
			
				this.popStyle = style;
				this.pickerUserIndex = Number(index);
				this.showShade = true;
				this.$nextTick(() => {
					setTimeout(() => {
						this.showPop = true;
					}, 10);
				});
			},
			/* 隐藏弹窗 */
			hidePop() {
				this.showPop = false;
				this.pickerUserIndex = -1;
				setTimeout(() => {
					this.showShade = false;
				}, 250);
			},
			/* 选择菜单 */
			pickerMenu(e) {
				let index = Number(e.currentTarget.dataset.index);
				//console.log(`第${this.pickerUserIndex+1}个用户,第${index+1}个按钮`);
				// 在这里开启你的代码秀
			
				uni.showToast({
					title: '开发者:小克',
					icon: "none",
					mask: true,
					duration: 600
				});
			
				/* 
				 因为隐藏弹窗方法中会将当前选择的用户下标还原为-1,
				 如果行的菜单方法存在异步情况，请在隐藏之前将该值保存，或通过参数传入异步函数中
				 */
				this.hidePop();
			}
		}
			
	}
</script>

<style lang="scss" scoped>
	@import url('@/static/css/navigate-bar.css');
	/* 列式弹性盒子 */
	.flex_col {
		display: flex;
		flex-direction: row;
		flex-wrap: nowrap;
		justify-content: flex-start;
		align-items: center;
		align-content: center;
	}
	
	/* 弹性盒子弹性容器 */
	.flex_col .flex_grow {
		width: 0;
		-webkit-box-flex: 1;
		-ms-flex-positive: 1;
		flex-grow: 1;
	}
	
	.flex_row .flex_grow {
		-webkit-box-flex: 1;
		-ms-flex-positive: 1;
		flex-grow: 1;
	}
	
	/* 弹性盒子允许换行 */
	.flex_col.flex_wrap {
		-ms-flex-wrap: wrap;
		flex-wrap: wrap;
	}
	
	/* 列表 */
	.list {
		background-color: #fff;
		font-size: 28upx;
		color: #333;
		user-select: none;
		touch-callout: none;
	
		&>view {
			padding: 24upx 30upx;
			position: relative;
	
			&:active,
			&.active {
				background-color: #f3f3f3;
			}
			
			.avatar-container{
				height: 90upx;
				width: 90upx;
				border-radius: 4px;
				margin-right: 20upx;
				position: relative;
			}
			image {
				height: 90upx;
				width: 90upx;
				// border-radius: 4px;
				// margin-right: 20upx;
			}
	
			&>view {
				line-height: 40upx;
	
				.time,
				.info {
					color: #999;
					font-size: 24upx;
				}
	
				.time {
					width: 150upx;
					text-align: right;
				}
	
				.info {
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}
			}
		}
	
		&>view:not(:first-child) {
			margin-top: 1px;
	
			&::after {
				content: '';
				display: block;
				height: 0;
				border-top: #CCC solid 1px;
				width: 620upx;
				position: absolute;
				top: -1px;
				right: 0;
				transform:scaleY(0.5);	/* 1px像素 */
			}
		}
	}
	
	/* 遮罩 */
	.shade {
		position: fixed;
		z-index: 100;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		-webkit-touch-callout: none;
	
		.pop {
			position: fixed;
			z-index: 101;
			width: 200upx;
			box-sizing: border-box;
			font-size: 28upx;
			text-align: left;
			color: #333;
			background-color: #fff;
			box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
			line-height: 80upx;
			transition: transform 0.15s ease-in-out 0s;
			user-select: none;
			-webkit-touch-callout: none;
			transform: scale(0, 0);
	
			&.show {
				transform: scale(1, 1);
			}
	
			&>view {
				padding: 0 20upx;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				user-select: none;
				-webkit-touch-callout: none;
	
				&:active {
					background-color: #f3f3f3;
				}
			}
		}
	}
	
</style>
